#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Christopher Durand
# Copyright (c) 2022-2023, Raphael Lehmann
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

class Instance(Module):
    def __init__(self, instance):
        self.instance = instance

    def init(self, module):
        module.name = str(self.instance)
        module.description = "Instance {}".format(self.instance)

    def prepare(self, module, options):
        return True

    def build(self, env):
        device = env[":target"]
        driver = device.get_driver("mcan")

        properties = {}
        properties["target"] = target = device.identifier
        properties["driver"] = driver
        properties["id"] = self.instance
        properties["reg"] = 'MCAN{}'.format(self.instance)

        env.substitutions = properties
        env.outbasepath = "modm/src/modm/platform/can"

        env.template("can_instance.hpp.in", "can_{}.hpp".format(self.instance))
        env.template("can_interrupt.cpp.in", "can_interrupt_{}.cpp".format(self.instance))


def init(module):
    module.name = ":platform:can"
    module.description = "Controller Area Network with Flexible Data-Rate (MCAN)"

def prepare(module, options):
    device = options[":target"]
    if not device.has_driver("mcan:sam*"):
        return False
    if device.identifier.variant == 'a':
        return False

    module.depends(
        ":architecture:assert",
        ":architecture:can",
        ":architecture:clock",
        ":cmsis:device",
        ":platform:can.common",
        ":platform:can.common.fdcan",
        ":platform:gpio")

    driver = device.get_driver("mcan")

    # Ignore duplicate instances, because modm-devices data is buggy
    instances = list(dict.fromkeys(listify(driver["instance"])))

    for instance in instances:
        module.add_submodule(Instance(int(instance)))

    return True

def build(env):
    env.outbasepath = "modm/src/modm/platform/can"
    env.copy("can.hpp")
    env.copy("can_impl.hpp")
    env.copy("can_message_ram_defaults.hpp")
